package com.leo.listener;

import com.leo.event.Event;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: EventMulticaster
 * @Description: 事件广播器
 * @Author: leo825
 * @Date: 2020-02-17 00:34
 * @Version: 1.0
 */
public class EventMulticaster {

    /**
     * 监听器列表
     */
    private static List<EventListener> listeners = new ArrayList<>();

    /**
     * 添加监听器
     *
     * @param eventListener
     * @return
     */
    public EventMulticaster addListener(AbstractEventListener eventListener) {
        listeners.add(eventListener);
        listeners = listeners.stream()
                .sorted(Comparator.comparing(EventListener::getSort))
                .collect(Collectors.toList());
        return this;
    }

    /**
     * 广播事件
     *
     * @param event
     */
    public void muticasterEvent(Event event) {
        for (EventListener eventListener : listeners) {
            eventListener.onEvent(event);
        }
    }
}
